//
//  JYOAuthAccountTool.m
//  FpdCarInCube
//
//  Created by WXC on 2017/4/11.
//  Copyright © 2017年 jiaoyin. All rights reserved.
//

#import "JYOAuthAccountTool.h"


@implementation JYOAuthAccountTool

/**
 *  存储账号信息
 *
 */
+ (void)saveAccount:(NSDictionary *)dict
{
    [JYOAuthAccount accountWithDict:dict];
    NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
    JYWriteToPlist(data, @"userData");
}


/**
 *  返回账号信息
 */
+ (JYOAuthAccount *)account
{
    // 加载plist文件
    NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"userData.plist"];
    NSData *data = [NSData dataWithContentsOfFile:filePath];
    if (data) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        return [JYOAuthAccount accountWithDict:dict];
    }
    return nil;
}

//+ (BOOL)isAccountAccess_tokenOverdue
//{
//    // 加载模型
//    OAuthAccount *account = [NSKeyedUnarchiver unarchiveObjectWithFile:OAuthAccountPath];
//    /* 验证账号是否过期 */
//    // 过期的秒数
//    long long expires_in = [account.expires_in longLongValue] - (10*60); // 提前10分钟判断过期
//    // 获得过期时间
//    NSDate *expiresTime = [account.created_time dateByAddingTimeInterval:expires_in];
//    // 获得当前时间
//    NSDate *now = [NSDate date];
//    // 如果expiresTime <= now，过期
//    /**
//     NSOrderedAscending = -1L, 升序，右边 > 左边
//     NSOrderedSame, 一样
//     NSOrderedDescending 降序，右边 < 左边
//     */
//    NSComparisonResult result = [expiresTime compare:now];
//    if (result != NSOrderedDescending) { // 过期
//        return YES;
//    }
//    return NO;
//}


+ (void)removeAccount
{
    NSFileManager *fmanager=[NSFileManager defaultManager];
    NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"userData.plist"];
    [fmanager removeItemAtPath:filePath error:nil];
}

// 认证时的头部信息
+ (NSDictionary *)getHeaderDic
{
    NSMutableDictionary *headerDic = [NSMutableDictionary dictionary];
    if ([JYOAuthAccount sharedJYOAuthAccount].Token.length) {
        [headerDic safeSetObject:[JYOAuthAccount sharedJYOAuthAccount].Token forKey:@"Token"];
//        [headerDic safeSetObject:[JPUSHService registrationID] forKey:@"registrationID"];
        return headerDic;
    }
    else
    {
        [ShowInfoView showMessage:@"token为空值"];
    }
    
    return nil;
}


/**
 保存登录状态
 */
+ (void)saveIsLogin
{
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:ISLOGIN];
    [[NSUserDefaults standardUserDefaults] synchronize];
}


/**
 是否登录
 */
+ (BOOL)isLogin
{
    return  [[NSUserDefaults standardUserDefaults] boolForKey:ISLOGIN];
}

/**
 移除登录状态
 */
+ (void)removeIsLogin
{
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:ISLOGIN];
    [[NSUserDefaults standardUserDefaults] synchronize];
}


@end
